package organ

import (
	"encoding/csv"
	"encoding/json"
	"fmt"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"go-papers/logic"

	"go-papers/models"
	"go-papers/pkg/lognew"
	"go-papers/tools"
	"go-papers/tools/app"
	"go-papers/tools/app/msg"
)

func DownCourseList(c *gin.Context) {
	var data models.Course
	var err error
	var pageSize = 30
	var pageIndex = 1

	if index := c.Request.FormValue("courseId"); index != "" {
		data.CourseId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("organId"); index != "" {
		data.OrganId = tools.StrToInt(err, index)
	}
	data.CourseStatus = c.Request.FormValue("courseStatus")
	data.CourseName = c.Request.FormValue("courseName")
	data.CourseImg = c.Request.FormValue("courseImg")
	data.CourseType = c.Request.FormValue("courseType")
	data.CourseCategory = c.Request.FormValue("courseCategory")
	data.OrganName = c.Request.FormValue("organName")
	data.BrandName = c.Request.FormValue("brandName")
	data.CourseTeach = c.Request.FormValue("courseTeach")
	if index := c.Request.FormValue("coursePrice"); index != "" {
		data.CoursePrice = tools.StringToFloat64(err, index)
	}
	if index := c.Request.FormValue("discountPrice"); index != "" {
		data.DiscountPrice = tools.StringToFloat64(err, index)
	}
	data.CourseTime = c.Request.FormValue("courseTime")
	data.CourseAge = c.Request.FormValue("courseAge")
	data.CreateBy = c.Request.FormValue("createBy")
	data.UpdateBy = c.Request.FormValue("updateBy")
	data.UpdateStart = c.Request.FormValue("updateStart")
	data.UpdateEnd = c.Request.FormValue("updateEnd")
	uid := tools.GetUserIdStr(c)
	if uid == "" {
		app.OK(c, nil, "请登陆后操作数据")
		return
	}
	data.DataScope = tools.GetUserIdStr(c)
	result, count, err := data.GetPage(pageSize, pageIndex) // 机构课程
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	header := []string{"课程名ID", "课程名称", "授课方式", "年龄段", "学科科目", "上课时间", "原价", "现价", "更新时间", "品牌名称", "机构名称", "上传人"} //标题
	cellist := [][]string{
		header,
	}
	cellist = DataToStringV5(result, cellist)

	page := count/pageSize + 1

	for i := 2; i <= page; i++ {
		pageIndex = i
		result, _, _ = data.GetPage(pageSize, pageIndex) // 下载导出
		if len(result) <= 0 {
			break
		}
		cellist = DataToStringV5(result, cellist)
	}

	// 创建文件
	filepath := "static/"
	filename := "Course_" + time.Now().Format("20060102150405") + ".csv"
	newFile, err := os.Create(filepath + filename)
	if err != nil {
		app.OK(c, nil, err.Error())
		return
	}
	defer func() {
		newFile.Close()

		err := os.Remove(filepath + filename)
		if err != nil {
			// 删除失败
			lognew.Info(c, "导出文件-清理失败", lognew.Fields{"file": filepath + filename, "err": err.Error()})
		}

	}()

	// 写入UTF-8
	newFile.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM，防止中文乱码
	// 写数据到csv文件
	w := csv.NewWriter(newFile)
	// WriteAll方法使用Write方法向w写入多条记录，并在最后调用Flush方法清空缓存。
	w.WriteAll(cellist)
	w.Flush()

	c.File(filepath + filename)

}

// OrganTeacher
// "课程名称",  "授课方式","年龄段","学科科目","上课时间","原价", "现价", "更新时间", "品牌名称","机构名称","上传人"
func DataToStringV5(list []models.Course, data [][]string) [][]string {
	for i := 0; i < len(list); i++ {
		context := []string{
			strconv.Itoa(list[i].CourseId),
			list[i].CourseName,
			list[i].CourseTeach,
			list[i].CourseAge,
			list[i].CourseCategory,
			list[i].CourseTime,
			tools.Float64ToString(list[i].CoursePrice),
			tools.Float64ToString(list[i].DiscountPrice),
			list[i].UpdatedAt.Format("2006-01-02 15:04:05"),
			list[i].BrandName,
			list[i].OrganName,
			list[i].CreateBy,
		}
		data = append(data, context)
	}
	return data
}

func GetCourseList(c *gin.Context) {
	var data models.Course
	var err error
	var pageSize = 10
	var pageIndex = 1

	if size := c.Request.FormValue("pageSize"); size != "" {
		pageSize = tools.StrToInt(err, size)
	}
	if index := c.Request.FormValue("pageIndex"); index != "" {
		pageIndex = tools.StrToInt(err, index)
	}

	if index := c.Request.FormValue("courseId"); index != "" {
		data.CourseId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("organId"); index != "" {
		data.OrganId = tools.StrToInt(err, index)
	}
	data.CourseStatus = c.Request.FormValue("courseStatus")
	data.CourseName = c.Request.FormValue("courseName")
	data.CourseImg = c.Request.FormValue("courseImg")
	data.CourseType = c.Request.FormValue("courseType")
	data.CourseCategory = c.Request.FormValue("courseCategory")
	data.OrganName = c.Request.FormValue("organName")
	data.BrandName = c.Request.FormValue("brandName")
	data.CourseTeach = c.Request.FormValue("courseTeach")
	if index := c.Request.FormValue("coursePrice"); index != "" {
		data.CoursePrice = tools.StringToFloat64(err, index)
	}
	if index := c.Request.FormValue("discountPrice"); index != "" {
		data.DiscountPrice = tools.StringToFloat64(err, index)
	}
	data.CourseTime = c.Request.FormValue("courseTime")
	data.CourseAge = c.Request.FormValue("courseAge")
	data.CreateBy = c.Request.FormValue("createBy")
	data.UpdateBy = c.Request.FormValue("updateBy")
	data.UpdateStart = c.Request.FormValue("updateStart")
	data.UpdateEnd = c.Request.FormValue("updateEnd")

	data.DataScope = tools.GetUserIdStr(c)
	result, count, err := data.GetPage(pageSize, pageIndex) //课程列表
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	app.PageOK(c, result, count, pageIndex, pageSize, "")
}
func UpdateStatusCourse(c *gin.Context) {
	var data models.Course
	data.CourseId, _ = tools.StringToInt(c.Request.FormValue("courseId"))
	result, err := data.Get()
	if err != nil {
		app.ApiResp(c, -1, "抱歉未找到相关信息："+err.Error(), data)
		return
	}

	var user models.SysUser
	uidInfo, _ := user.GetById(tools.GetUserId(c))
	if uidInfo.UserType == "3" {
		data.OrganId = uidInfo.OrganId
		data.OrganName = uidInfo.OrganName
	}

	data.CourseStatus = c.Request.FormValue("courseStatus")
	res, err := data.Update(result.CourseId) //UpdateStatusCourse
	if err != nil {
		app.ApiResp(c, -1, "更新失败-相关信息："+err.Error(), data)
		return
	}
	app.OK(c, res, "修改成功")
}
func GetCourse(c *gin.Context) {
	var data models.Course
	data.CourseId, _ = tools.StringToInt(c.Param("id"))
	result, err := data.Get()
	if err != nil {
		app.ApiResp(c, -2, "抱歉未找到相关信息："+err.Error(), nil)
		return
	}

	app.OK(c, result, "")
}

func InsertCourse(c *gin.Context) {
	var data models.Course
	err := c.ShouldBindJSON(&data)
	data.CreateBy = tools.GetUserIdStr(c)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}

	data.UpdateBy = tools.GetUserIdStr(c)
	data.CreateBy = tools.GetUserIdStr(c)
	data.CreateByName = tools.GetUserName(c)
	data.UpdateByName = tools.GetUserName(c)
	// 计算完成度
	ret := make(map[string]interface{})
	ss, _ := json.Marshal(data)
	_ = json.Unmarshal(ss, &ret)

	l := len(ret)
	m := 0.0
	for _, v := range ret {
		if v == "" {
			m += 1
		}
	}
	p := m / float64(l) * 100
	data.CourseFinish = fmt.Sprintf("%.0f", p)

	var user models.SysUser
	uidInfo, _ := user.GetById(tools.GetUserId(c))
	if uidInfo.UserType == "3" {
		data.OrganId = uidInfo.OrganId
		data.OrganName = uidInfo.OrganName
	}
	data.RealPrice = data.CoursePrice - data.DiscountPrice
	result, err := data.Create()
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	app.OK(c, result, "新增成功")
}

func UpdateCourse(c *gin.Context) {
	var data models.Course
	err := c.ShouldBindJSON(&data)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}

	// 计算完成度
	ret := make(map[string]interface{})
	ss, _ := json.Marshal(data)
	_ = json.Unmarshal(ss, &ret)

	l := len(ret)
	m := 0.0
	for _, v := range ret {
		if v == "" {
			m += 1
		}
	}
	p := m / float64(l) * 100
	data.CourseFinish = fmt.Sprintf("%.0f", p)
	if data.DiscountPrice < 0.1 {
		data.DiscountPrice = 0.00
	}
	data.UpdateBy = tools.GetUserIdStr(c)
	data.CreateBy = tools.GetUserIdStr(c)
	data.UpdateByName = tools.GetUserName(c)
	data.CreateByName = tools.GetUserName(c)

	data.RealPrice = data.CoursePrice - data.DiscountPrice
	result, err := data.Update(data.CourseId) // UpdateCourse
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	data.UpdateDiscountPrice(data.CourseId, data.DiscountPrice)
	data.UpdateCoursePrice(data.CourseId, data.CoursePrice)
	realPrice := data.CoursePrice - data.DiscountPrice
	data.UpdateCourseRealPrice(data.CourseId, realPrice)

	app.OK(c, result, "编辑成功")
}

func CheckCourse(c *gin.Context) {
	var data models.Course
	var checkReq models.CheckReq
	err := c.BindWith(&checkReq, binding.JSON)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}

	data.CourseId = checkReq.Id
	data.CourseStatus = checkReq.ApprovalStatus
	data.ApprovalUserId = tools.GetUserIdStr(c)
	data.ApprovalUserName = tools.GetUserName(c)
	data.ApprovalAt = time.Now().Format("2006-01-02 15:04:05")
	result, err := data.Update(data.CourseId)
	if err != nil {
		tools.HasError(err, "操作失败"+err.Error(), -1)
	}

	//1,2,3
	var organ models.Organ
	organInfo, _ := organ.GetByID(result.OrganId)
	str := organInfo.OrganCourseType
	if str != "" {
		strArr := strings.Split(str, ",")
		strArr = append(strArr, result.CourseType)
		organInfo.OrganCourseType = strings.Join(strArr, ",")
	} else {
		organInfo.OrganCourseType = result.CourseType + ","
	}

	if organInfo.OrganMomId != 0 {
		//查询
		var mmm models.Member
		mmmInfo, _ := mmm.GetByID(organInfo.OrganMomId)
		organInfo.MomCode = mmmInfo.MemberCode
		organInfo.MomTel = mmmInfo.Phone
		organInfo.OrganMomName = mmmInfo.RealName
		organInfo.OrganMomId = mmmInfo.MemberId
	}
	_, _ = organInfo.Update(organInfo.OrganId) // 审核

	// 更新机构达人的 机构数
	logic.UpdateOrganMomNums(organInfo.OrganMomId)

	app.OK(c, result, "")
}

func DeleteCourse(c *gin.Context) {
	var data models.Course

	IDS := tools.IdsStrToIdsIntGroupV3("courseId", c)
	_, err := data.BatchDelete(IDS)
	if err != nil {
		app.ApiResp(c, -1, "数据删除失败："+err.Error(), IDS)
		return
	}

	app.OK(c, IDS, msg.DeletedSuccess)
}
